import React from 'react';
import PropTypes from 'prop-types';

export default class VoteClazz extends React.PureComponent{

    constructor(props){
        //es6要求调用this.就必须使用super
        super(props);//会把传递进来的属性挂载到this实例上
        this.state = {
            name:'hello world',
            count:0
        }
    }

    //在没有constructor的情况下初始化state
    // state = {
    //     name:'hello world'
    // }


    //规则校验
    static defaultProps = {
        num:PropTypes.number.isRequired,
        title:PropTypes.string.isRequired
    }


    render(){

        let {name,count} = this.state;

        return <div>
            <div>
            {this.props.num}
            </div>
            <div>
                num:{count}
            </div>
            <div>
                {name}
            </div>
            <button onClick={()=>{
                count++;
                this.setState({
                    count
                })
            }}>+</button>

            <button onClick={()=>{
                count--;
                this.setState({count})
                // this.forceUpdate();//强制更新视图
            }}>
                -
            </button>
        </div>
    }

    //是否允许组件更新
    shouldComponentUpdate(nextProps,nextState){

        //修改前的属性和状态

        let {props,state} = this;

        //修改后的属性和状态
        console.log(nextProps,'nextProps');
        console.log(nextState,'nextState');
        return true;
    }


    isObject(obj){
        return obj !== null && 
         /^(function | object)$/.test(typeof obj)
    };


    /**
     * 浅比较
     * @param {*} objA 
     * @param {*} objB 
     */
    shallowEqual(objA,objB){

        if(objA === objB){
            return true;
        }

        if(!this.isObject(objA)  || !this.isObject(objB)){
            return false;
        }

        //取键
        let oAKeys = Reflect.ownKeys(objA);
        let oBKeys = Reflect.ownKeys(objB);
        if(oAKeys.length != oBKeys.length){
            return false;
        }

        for(let i = 0;i < oAKeys.length;i++){

            let key = oAKeys[i];

            if(!objB.hasOwnProperty(key) || !Object.is(objA[key] , objB[key])){
                return false;
            }
        }

        return true;

    }
}